package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mapper.RoleMapper;
import com.qs.mapper.entity.Role;
import com.qs.service.RoleService;
import com.qs.service.bo.RoleBO;
import com.qs.util.BeanCopyUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Override
    public String add(RoleBO roleBO) {
        Role role = BeanCopyUtils.copyBean(roleBO, Role.class);
        isExist(Role::getName, role.getName());
        boolean saved = save(role);
        return saved ? "新增成功" : "新增失败";
    }

    @Override
    public String edit(RoleBO roleBO) {
        Role role = BeanCopyUtils.copyBean(roleBO, Role.class);
        isExist(Role::getName, role.getName());
        boolean updated = updateById(role);
        return updated ? "修改成功" : "修改失败";
    }

    private void isExist(SFunction<Role, ?> column, Object value) {
        LambdaQueryWrapper<Role> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(column, value);
        Role role = getOne(queryWrapper);
        if (Objects.nonNull(role)) {
            throw new RuntimeException("角色已存在");
        }
    }
}
